import { generateUUID } from '@/utils/tools';
export function parseTime(time, cFormat) {
  if (!time) return null;
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ]; }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
}

// 获取当天的零点 或 59分时间
export function getCurrentZeroTime(timestamp, type = 0) { // type 1： 59分；0： 0分
  let date;
  let isMsec = true;
  if (timestamp) {
    let timeData;
    if (timestamp.toString().length === 10) {
      timeData = timestamp * 1000;
      isMsec = false;
    } else {
      timeData = timestamp;
    }
    date = new Date(timeData);
  } else {
    date = new Date();
  }
  let month = parseInt(date.getMonth() + 1);
  let day = date.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  const firstDate = (date.getFullYear() + '-' + month + '-' + day).replace(/-/g, '/');
  const firstDateObj = new Date(firstDate);
  if (type) {
    firstDateObj.setHours(23, 59, 59, 0);
  } else {
    firstDateObj.setHours(0, 0, 0, 0);
  }
  if (isMsec) {
    return firstDateObj.getTime();
  } else {
    return firstDateObj.getTime() / 1000;
  }
}

// 获取当前月份的第一天
export function getCurrentMonthFirst(timestamp) {
  let date;
  if (timestamp) {
    date = new Date(timestamp);
  } else {
    date = new Date();
  }
  date.setDate(1);
  let month = parseInt(date.getMonth() + 1);
  let day = date.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  const firstDate = (date.getFullYear() + '-' + month + '-' + day).replace(/-/g, '/');
  const firstDateObj = new Date(firstDate);
  firstDateObj.setHours(0, 0, 0, 0);
  return firstDateObj.getTime();
}

// 获取当前月份的最后一天
export function getCurrentMonthLast(timestamp) {
  let date;
  if (timestamp) {
    date = new Date(timestamp);
  } else {
    date = new Date();
  }
  let currentMonth = date.getMonth();
  const nextMonth = ++currentMonth;
  const nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  const oneDay = 1000 * 60 * 60 * 24;
  const lastTime = new Date(nextMonthFirstDay - oneDay);
  let month = parseInt(lastTime.getMonth() + 1);
  let day = lastTime.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  const lastDate = (date.getFullYear() + '-' + month + '-' + day).replace(/-/g, '/');
  const lastDateObj = new Date(lastDate);
  lastDateObj.setHours(23, 59, 59, 0);
  return lastDateObj.getTime();
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

/**
 * 防抖函数，返回函数连续调用时，空闲时间必须大于或等于 wait，func 才会执行
 *
 * @param  {function} func        回调函数
 * @param  {number}   wait        表示时间窗口的间隔
 * @param  {boolean}  immediate   设置为ture时，是否立即调用函数
 * @return {function}             返回客户调用函数
 */
export function debounce(func, wait = 50, immediate = false) {
  let timer, context, args;
  // 延迟执行函数
  const later = () => setTimeout(() => {
    // 延迟函数执行完毕，清空缓存的定时器序号
    timer = null;
    if (!immediate) {
      func.apply(context, args);
      context = args = null;
    }
  }, wait);
  return function(...params) {
    if (!timer) {
      timer = later();
      if (immediate) {
        func.apply(this, params);
      } else {
        context = this;
        args = params;
      }
    } else {
      clearTimeout(timer);
      timer = later();
    }
  };
}

/**
 *  节流函数
 * @param {number} delay
 * @param {function} fn
 */
export function thorttle(fn, delay = 1000) {
  let lastTime = '';
  let timer = '';
  const interval = delay;
  return function() {
    const args = arguments;
    const nowTime = Date.now();
    if (lastTime && nowTime - lastTime < interval) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        lastTime = nowTime;
        fn.apply(this, args);
      }, interval);
    } else {
      lastTime = nowTime;
      fn.apply(this, args);
    }
  };
}

export function handelDepartmentData(data) {
  if (data && data.length > 0) {
    data.forEach((item, index) => {
      item.value = item.userName && item.userName !== '' ? item.userName : item.departmentName;
      item.id = item.userId || (index + 1);
      item.isDepartment = !(item.userName && item.userName !== '');
      item.leaf = !!(item.userName && item.userName !== '');
      // if (!(item.children && item.children.length)) {
      //   item.children = null;
      // }
      handelDepartmentData(item.children);
    });
  }
}

let pathList = [];
// 遍历部门树状结构 获取 节点路径
export function getDepartmentTreePath(root) {
  pathList = [];
  listPath(root, []);
  return pathList;
}

const listPath = function(root, path) {
  if (!(root.children && root.children.length)) {
    path.push(root.id);
    pathList.push(path);
  } else {
    path.push(root.id);
    const childs = root.children;
    let i = 0;
    const tempPath = [...path];
    while (i < childs.length) {
      listPath(childs[i], [...tempPath]);
      i++;
    }
  }
};

// 去重
export function uniq(arr, key) {
  const result = [];
  const obj = {};
  arr.forEach(i => {
    if (!obj[i[key]]) {
      result.push(i);
      obj[i[key]] = 1;
    }
  });
  return result;
}
/** 下载文件 */
export function downloadFile(url, filename) {
  getBlob(url, function(blob) {
    saveAs(blob, filename);
  });
}
function getBlob(url, cb) {
  var xhr = new XMLHttpRequest();
  // url加时间戳解决从缓存获取导致跨域问题
  xhr.open('GET', url + '?t=' + new Date().getTime(), true);
  xhr.responseType = 'blob';
  xhr.onload = function() {
    if (xhr.status === 200) {
      cb(xhr.response);
    }
  };
  xhr.send();
}
function saveAs(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    var link = document.createElement('a');
    var body = document.querySelector('body');

    link.href = window.URL.createObjectURL(blob);
    link.download = filename || '--';

    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}

// 打开新窗口（防止window.open被拦截） 类似window.open(href, '_blank')
export function openNewWindow(url, id = 'id_a_for_win_open') {
  let a = document.getElementById(id);
  if (!a) {
    // 防止反复添加
    a = document.createElement('a');
    a.setAttribute('href', url);
    a.setAttribute('target', '_blank');
    // a.setAttribute('target', '_system');
    a.setAttribute('id', id);
    document.body.appendChild(a);
  } else {
    a.setAttribute('href', url);
  }
  a.click();
}

export function parseJson(data) {
  try {
    return JSON.parse(data);
  } catch (error) {
    return data;
  }
}

export function strJsonParse(str) {
  if (str && str !== '') {
    try {
      return JSON.parse(str);
    } catch (e) {
      return false;
    }
  }
  return false;
}

// 用于对比信息通用取值方法
export function getTargetData(data, field) {
  return data ? (data[field] === 0 ? data[field] : (data[field] || '--')) : '--';
}
// 提取数组某一字段，拼接成 xxx, xxx 的格式
export function jointFun(data, filed) {
  let arr = [];
  if (data instanceof Array && data && data.length > 0) arr = data.map(item => item[filed]);
  if (arr.length > 0) {
    return arr.join(',');
  } else {
    return '--';
  }
}

// 深拷贝 并且 有一个基础数据 对比两组数据 如果一致则用详情的数据赋值，且遇到字段为null的字段转换为''字符串 obj: 原始数据，detail详情数据
export function valuationData(obj, detail) {
  const objClone = Array.isArray(obj) ? [] : {};
  const detailTemp = detail;
  if (obj && typeof obj === 'object') {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        // 判断ojb子元素是否为对象，如果是，递归复制
        if (obj[key] && (typeof obj[key] === 'object' && !(obj[key] instanceof Array))) {
          let vaildDetail;
          if (!detailTemp[key]) {
            vaildDetail = JSON.parse(JSON.stringify(obj[key]));
          } else {
            vaildDetail = detailTemp[key];
          }
          // console.log(obj[key], detailTemp[key], key);
          objClone[key] = valuationData(obj[key], vaildDetail);
        } else {
          // 如果不是，简单复制
          let value;
          if (detailTemp[key] === 0 || detailTemp[key]) {
            value = detailTemp[key];
          } else {
            value = obj[key];
          }
          objClone[key] = value;
        }
      }
    }
  }
  return objClone;
}

// 深拷贝
export function deepClone(obj) {
  const objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === 'object') {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        // 判断ojb子元素是否为对象，如果是，递归复制
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = deepClone(obj[key]);
        } else {
          // 如果不是，简单复制
          const value = obj[key] !== 0 ? (obj[key] || null) : obj[key];
          objClone[key] = value;
        }
      }
    }
  }
  return objClone;
}

export const encryption = function(id) {
  try {
    const frontSalt = Math.ceil(Math.random() * (99999 - 10000) + 10000);
    const endSalt = Math.ceil(Math.random() * (99999 - 10000) + 10000);
    return btoa(`${frontSalt}${id}${endSalt}`);
  } catch (error) {
    return id;
  }
};
export const decrypt = function(crypt) {
  if (!crypt) return crypt;
  try {
    if (crypt.length > 10) {
      crypt = atob(crypt);
      crypt = crypt.replace(crypt.substring(0, 5), '');
      crypt = crypt.replace(crypt.substring(crypt.length - 5), '');
    }
    return crypt;
  } catch (error) {
    return crypt;
  }
};

/**
 * 获取上、下个月时间戳
 * @param addMonth -1上个月，+1下个月
 */
export const getMonthStr = function(addMonth) { // 获取上个月日期
  if (!addMonth) return '';
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1 + addMonth;
  const result = new Date(`${year}-${month}`).valueOf();
  return result;
};
/**
 * 为对象内所有列表增加唯一值
 */
export const setListUuid = function(params, listKeys = []) {
  const union_list_key = generateUUID();
  listKeys.forEach(i => {
    const keys = i.split('.');
    const resultArr = keys.reduce((res, key) => res[key], params);
    if (resultArr && resultArr.length) {
      resultArr.map(j => {
        if (!j.union_list_key) {
          j.union_list_key = union_list_key;
        }
      });
    }
  });
};
/**
 * 通过id获取部门name
 */
export const getDeptName = function(id, deptList = []) {
  if (!id || !Array.isArray(deptList) || !deptList.length) {
    return '';
  }
  for (let i = 0; i < deptList.length; i++) {
    const a = deptList[i];
    if (a.id === id) {
      return a.name;
    } else {
      if (a.children && a.children.length > 0) {
        const res = getDeptName(id, a.children);
        if (res) {
          return res;
        }
      }
    }
  }
  return '';
};
// // 获取用户第一个部门的第一个子级部门
export function getFirstDepartment(list) {
  if (Array.isArray(list) && list.length) {
    const deptIdArr = list[0].id;
    if (Array.isArray(deptIdArr) && deptIdArr.length) {
      return deptIdArr[deptIdArr.length - 1];
    } else {
      return null;
    }
  } else {
    return null;
  }
}

// 模拟ping地址
export const pingIpAddress = (url, timeout = 6000) => {
  return new Promise((resolve, reject) => {
    const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]');
    if (!urlRule.test(url)) reject('无效地址');
    try {
      fetch(url)
        .then(() => resolve(true))
        .catch(() => resolve(false));
      setTimeout(() => {
        resolve(false);
      }, timeout);
    } catch (e) {
      reject(e);
    }
  });
};
